package com.ytjj.qmyx.mall.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.ytjj.common.api.CommonPage;
import com.ytjj.common.exception.ApiException;
import com.ytjj.common.service.RedisService;
import com.ytjj.qmyx.mall.constants.RedisConstants;
import com.ytjj.qmyx.mall.enums.SubjectsEnum;
import com.ytjj.qmyx.mall.mapper.ProductSubjectPlateDao;
import com.ytjj.qmyx.mall.mapper.SubjectPlateMapper;
import com.ytjj.qmyx.mall.mapper.SubjectsMapper;
import com.ytjj.qmyx.mall.model.SubjectPlate;
import com.ytjj.qmyx.mall.model.SubjectPlateExample;
import com.ytjj.qmyx.mall.model.Subjects;
import com.ytjj.qmyx.mall.model.UsersFake;
import com.ytjj.qmyx.mall.model.dto.ProductSubjectPlateDto;
import com.ytjj.qmyx.mall.model.dto.SubjectPlateDto;
import com.ytjj.qmyx.mall.model.dto.SubjectPlateProductDto;
import com.ytjj.qmyx.mall.model.dto.SubjectsDto;
import com.ytjj.qmyx.mall.service.SubjectsService;
import com.ytjj.qmyx.mall.utils.DateUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Random;
import java.util.stream.Collectors;

/**
 *
 * 
 * @description:
 */
@Service
public class SubjectsServiceImpl implements SubjectsService {
    @Resource
    private SubjectPlateMapper subjectPlateMapper;
    @Resource
    private ProductSubjectPlateDao productSubjectPlateDao;
    @Resource
    private SubjectsMapper subjectsMapper;
    @Autowired
    private RedisService redisService;

    @Override
    public SubjectsDto getSubjectsById(Integer id) {
        SubjectsDto subjectsDto = new SubjectsDto();
        //1.获取专题信息
        Subjects subjects = subjectsMapper.selectByPrimaryKey(id);
        if(subjects == null ){
            throw new ApiException("专题不存在");
        }
        BeanUtils.copyProperties(subjects,subjectsDto);
        //2.获取专题下板块
        List<SubjectPlateDto> plateBySubjectList = this.getPlateBySubjectId(subjectsDto.getId());

        //3.设置板块下的商品
        plateBySubjectList.stream().forEach(e->{
            CommonPage<ProductSubjectPlateDto> productByPlateId = this.getProductByPlateId(e.getId(),1,10);
            e.setProductSubjectPlateList(productByPlateId.getList());
        });
        //4.保存板块到专题
        subjectsDto.setSubjectPlateDtos(plateBySubjectList);
        return subjectsDto;
    }


    @Override
    public List<SubjectPlateDto> getPlateBySubjectId(Integer subjectId) {
        List<SubjectPlateDto> subjectPlateDtos = new ArrayList<>();
        SubjectPlateExample subjectPlateExample = new SubjectPlateExample();
        subjectPlateExample.createCriteria().andSubjectIdEqualTo(subjectId).andIsDeletedEqualTo(0);
        subjectPlateExample.setOrderByClause("sort desc");
        List<SubjectPlate> subjectPlates = subjectPlateMapper.selectByExample(subjectPlateExample);
        subjectPlates.stream().forEach(e->{
            SubjectPlateDto subjectPlateDto = new SubjectPlateDto();
            BeanUtils.copyProperties(e,subjectPlateDto);
            subjectPlateDtos.add(subjectPlateDto);
        });
        return subjectPlateDtos;
    }

    @Override
    public CommonPage<ProductSubjectPlateDto> getProductByPlateId(Integer plateId,Integer pageNum,Integer pageSize) {
        PageHelper.startPage(pageNum,pageSize);
        List<ProductSubjectPlateDto> productByPlateId = productSubjectPlateDao.getProductByPlateId(plateId);

        List<Object> fakeUserListObject = redisService.range(RedisConstants.FAKE_USER, 0, -1);
        List<UsersFake> fakeUserslist = fakeUserListObject.stream()
                .map(item -> JSONObject.parseObject((String) item, UsersFake.class))
                .collect(Collectors.toList());
        productByPlateId.stream().forEach(item -> {
            Random random = new Random();
            int fromIndex = random.nextInt(fakeUserslist.size() - 3);
            List<UsersFake> newList = fakeUserslist.subList(fromIndex, fromIndex + 3);
            item.setUserImgList(newList.stream().map(UsersFake::getHeadImg).collect(Collectors.toList()));
        });
        return CommonPage.restPage(productByPlateId);
    }

    @Override
    public List<ProductSubjectPlateDto> getProductBySubjectId(Integer subjectId,String activeType) {
        List<ProductSubjectPlateDto> productsByActive = new ArrayList<>();
        if(SubjectsEnum.SECKILL.getActivityCode().equals(activeType)){
            productsByActive = this.getActiveProductByPlate(subjectId,activeType);
        }else if(SubjectsEnum.TOPBRAND_DISCOUNTS.getActivityCode().equals(activeType)){//只取第一个板块的商品
            //1.获得专题下的板块
            SubjectPlateExample subjectPlateExample = new SubjectPlateExample();
            subjectPlateExample.createCriteria().andSubjectIdEqualTo(subjectId).andIsDeletedEqualTo(0);
            subjectPlateExample.setOrderByClause("sort desc");
            List<SubjectPlate> subjectPlates = subjectPlateMapper.selectByExample(subjectPlateExample);
            //获取板块下的商品
            if(subjectPlates.size() == 0){
                return productsByActive;
            }
            productsByActive = productSubjectPlateDao.getProductByActiveAndPlateId(subjectPlates.get(0).getId(), activeType);
        }else{
            productsByActive = productSubjectPlateDao.getProductByActive(subjectId, activeType);
        }
        return productsByActive;
    }

    /**
    * 根据当前时间获得板块设定的时间区间下的商品
    * @param :
    * @returns: java.util.List<com.ytjj.qmyx.mall.model.dto.ProductSubjectPlateDto>
    * 
    */
    public List<ProductSubjectPlateDto> getActiveProductByPlate(Integer subjectId,String activeType){
        List<ProductSubjectPlateDto> productsByActive = new ArrayList<>();
        //1.获得专题下的板块
        SubjectPlateExample subjectPlateExample = new SubjectPlateExample();
        subjectPlateExample.createCriteria().andSubjectIdEqualTo(subjectId).andIsDeletedEqualTo(0);
        subjectPlateExample.setOrderByClause("sort desc");
        List<SubjectPlate> subjectPlates = subjectPlateMapper.selectByExample(subjectPlateExample);
        //升序
        List<SubjectPlate> subjectPlatesAsc = subjectPlates.stream().sorted(Comparator.comparing(SubjectPlate::getTitle)).collect(Collectors.toList());
        //获得当前时间
        String format = "HH:mm:ss";
        SimpleDateFormat sf = new SimpleDateFormat(format);
        String now = "13:00:00";
        for (int i = 0; i < subjectPlates.size(); i++) {
            //1.当前时间是否在设定时间内
            //只有一个版块
            if (i == 0 && i < subjectPlates.size()-1) {
                boolean a = DateUtils.isEffectiveTimeStr(now, "00:00:00", subjectPlates.get(i + 1).getTitle()+":00", format);
                //1.1 是，则取当前板块的商品
                if(a){
                    productsByActive = productSubjectPlateDao.getProductByActiveAndPlateId(subjectPlates.get(i + 1).getId(), activeType);
                }
            }else if(i < subjectPlates.size()-1){
                boolean a = DateUtils.isEffectiveTimeStr(now, subjectPlates.get(i).getTitle()+":00", subjectPlates.get(i + 1).getTitle()+":00", format);
                if(a){
                    productsByActive = productSubjectPlateDao.getProductByActiveAndPlateId(subjectPlates.get(i).getId(), activeType);
                }
            }else if(i == subjectPlates.size()-1){
                boolean a = DateUtils.isEffectiveTimeStr(now, subjectPlates.get(i).getTitle()+":00","24:00:00", format);
                if(a){
                    productsByActive = productSubjectPlateDao.getProductByActiveAndPlateId(subjectPlates.get(i).getId(), activeType);
                }
            }
        }
        return productsByActive;
    }

    @Override
    public SubjectsDto newGetSubjectsById(Integer id) {
        SubjectsDto subjectsDto = new SubjectsDto();
        //1.获取专题信息
        Subjects subjects = subjectsMapper.selectByPrimaryKey(id);
        if(subjects == null ){
            throw new ApiException("专题不存在");
        }
        BeanUtils.copyProperties(subjects,subjectsDto);
        //2.获取专题下板块
        List<SubjectPlateDto> plateBySubjectList = this.getPlateBySubjectId(subjectsDto.getId());

        //3.设置板块下的商品
        plateBySubjectList.stream().forEach(e->{
            CommonPage<ProductSubjectPlateDto> productByPlateId = this.newGetProductByPlateId(e.getId(),1,10);
            e.setProductSubjectPlateList(productByPlateId.getList());
        });
        //4.保存板块到专题
        subjectsDto.setSubjectPlateDtos(plateBySubjectList);
        return subjectsDto;
    }

    @Override
    public CommonPage<SubjectPlateProductDto> getSubjectProducts(Integer id, Integer pageNum, Integer pageSize) {
        if (null == id){
            id = 68;
        }
        PageHelper.startPage(pageNum,pageSize);
        List<SubjectPlateProductDto> productBySubjectId = productSubjectPlateDao.getSubjectProducts(id);
        productBySubjectId.stream().forEach(item ->{
            item.setSubsidizePrice(item.getCurPrice().subtract(item.getPrice()).setScale(0, BigDecimal.ROUND_DOWN));
            item.setPrice(item.getPrice().setScale(0, BigDecimal.ROUND_DOWN));
        });
        return CommonPage.restPage(productBySubjectId);
    }

    @Override
    public CommonPage<ProductSubjectPlateDto> newGetProductByPlateId(Integer plateId,Integer pageNum,Integer pageSize) {
        PageHelper.startPage(pageNum,pageSize);
        List<ProductSubjectPlateDto> productByPlateId = productSubjectPlateDao.getProductByPlateId(plateId);
        productByPlateId.stream()
                .filter(item -> null != item.getPercentage())
                .forEach(s -> s.setProductNum(s.getPercentage().intValue()));
        productByPlateId = productByPlateId.stream().filter(s -> null != s.getProductNum()).collect(Collectors.toList());
        productByPlateId = productByPlateId.stream().filter(s -> !s.getProductNum().equals(0)).collect(Collectors.toList());
        return CommonPage.restPage(productByPlateId);
    }
}
